<?php

/**
 * 牌九控制流程
 * User: yinchen
 * Date: 2017/12/19
*/
namespace app\game\controller;
use think\Session;
use think\Controller;
use think\Loader;
use think\Db;
use think\Log;
use app\common\model\Member;
class Card9 extends Controller {
	/**
	 * 保存组局信息到t_room ， 更新房主房间号
	 * 创建房间，成功后。初始化自己的状态account_status=0 online_status=1 room_id=room->id account_score=0 （积分清零） 扣房卡  jointime=time()   sort=1（ 座位设为1）
	 * 返回 当前局数 总局数  玩法
	 * roomStatus 房间游戏状态 0：准备好  1：发牌  2：
	 * islock   准备好的（坐下）人员是否已经满的状态  0：为锁定  1 锁定；坐下时，判断准备好的是否>=4，如过满则islock=1,站起时则islock=0;
	 * @return
	 * scucess:$result={ "operation": "CreateRoom", "result": 0, "result_message": "创建房间", "data": { "room_id": "375577", "room_number": "1b0e9b2n2qt", "total_num": 10, "game_num": 0, "banker_mode": 1, "game_type": 1 } }
	 * fail:$result=['result'=>1,'result_message'=>'创建失败']
	 *     $result=['result'=>1,'result_message'=>'房卡不足']
	 *     $result=['result'=>1,'result_message'=>'无效信息']
	 */
	public function CreateRoom(){
		$dataPost=$this->GetPost();
		$dataPost=array(
			'account_id'=>6035,
			'data'=>array(
				'ticket_type'=>2,
				'room_number'=>13,
				'banker_mode'=>2, //1 轮庄  2 固定庄  3 抢庄
				'rule_type'=>1, // 1房主支付 2 AA支付
				'score_type'=>1, //1比大小 2比倍
				'base_score'=>10, //1分 3分 5分 10分

			)
		);
		if(!$dataPost){
			return $this->ErrorInfo('CreateRoom','无效信息');
		}
		//判断是否是会员
		$memberInfo = $this->IsMember($dataPost['account_id'],'cards');
		if(!$memberInfo){
			return $this->ErrorInfo('CreateRoom','无效信息');
		}
		// 判断房卡是否足够
		if(isset($dataPost['data']['ticket_type'])){
			$ticket_type=$dataPost['data']['ticket_type'];
			$cards=$this->GetGameCards();
			if(array_key_exists($ticket_type,$cards)){
				if($memberInfo->cards > $cards[$ticket_type]*4){
					$result = $this->RoomCreate($dataPost);
					// Log::record($result);
					return json_encode($result);
				}
			}
		}
		return $this->ErrorInfo('CreateRoom','房卡不足');
	}

	/**
	 * 新增一个房间 成功后，扣房卡，更改自己的状态 account_status=0 online_status=1 room_id
	 * @param [type] $post [post提交的数据]
	 * @return [array]$result 返回结果
	 */
	private function RoomCreate($post){
		// 初始化参数
		$result = [];
		$num=$this->GetGameNums();//游戏次数数组
		$card=$this->GetGameCards();//游戏扣的房卡数组
		$ticket_type=$post['data']['ticket_type'];//前端传的房卡索引

		$result['operation'] = "CreateRoom";
		$result['result'] = 1;
		$result['result_message'] = "创建失败";
		if(!array_key_exists($ticket_type, $card)){
			return $result;
		}
		//房间号 时间戳加6位随机数，随后变成32进制字符串
		$data['room_number'] = time().rand(100000,999999);
		$data['room_number']=base_convert ($data['room_number'],10,32);
		// 添加数据
		$dbroom=model('room');
		$data['account_id'] = $post['account_id'];
		$data['ticket_type'] = $ticket_type;
		$data['total_num']=$num[$ticket_type];  //可进行的局数
		$data['banker_mode'] = $post['data']['banker_mode']; // 2固定庄
		$data['rule_type'] = $post['data']['rule_type'];  // 1 房主支付
		$data['score_type'] = $post['data']['score_type']; // 1比大小
		$data['base_score'] = $post['data']['base_score']; // 10分
		$data['room_status'] = 1;//房间的游戏状态，0未开始，1准备
		$data['game_num']=0;//游戏次数
		$data['islock']=0;//游戏开始后则锁定为1

		$data['starttime']=time();
		$ret=$dbroom->save($data);
		if(!$ret){
			return $result;
		}

		//开房间暂时扣金币,更新自己的房间号码
		$member=Member::get($post['account_id']);
		//$member->cards=($member->cards - $card[$ticket_type]);
		if($post['data']['banker_mode'] == 1 || $post['data']['banker_mode'] == 2){
			$member->is_banker=1; //轮庄，固定庄 房主为庄家   一轮结束后更改下一个位置的玩家为庄家
		}

		$member->room_id=$dbroom->id;
		$member->online_status=1;  //是否在线 1在线
		$member->account_status=0;
		$member->jointime=time();
		$member->sort=1;
		$member->account_score=0;//积分清零
		$member->save();
		// 返回成功结果
		$result['result'] = 0;
		$result['data']['room_id'] = $dbroom->id;
		$result['data']['room_number'] = $data['room_number'];
		$result['data']['total_num'] = $dbroom->total_num;
		$result['data']['game_num']=$dbroom->game_num;
		$result['data']['banker_mode']=$dbroom->banker_mode;
		$result['result_message'] = "创建房间";
		return $result;
	}

	/**
	 * 返回id对应人的某些字段数据
	 * @param int $id    [会员账号id]
	 * @param string $field 字段字符串
	 * @return obj $member  会员信息   | bool  false
	 */
	private function IsMember($id,$field='*'){
		//判断是否是会员
		if($field=='*'){
			$member = model('member')->where(['id' =>$id])->find();
		}else{
			$member = model('member')->where(['id' =>$id])->field($field)->find();
		}
		if(!$member)return false;
		return $member;
	}

	/**
	 * 取出提交的数据
	 * @param  post提交的数据
	 * @return array | false
	 */
	private function GetPost($flag='createroom'){
		$dataPost = json_decode(file_get_contents('php://input'), true);
		if(!isset($dataPost['account_id'])){// POST提交
			//点击链接Get传入参数
			if(isset($_GET['account_id']) && isset($_GET['room_number'])){
				$dataPost['account_id']=$_GET['account_id']+0;
				$dataPost['data']['room_number']=$_GET['room_number'];
			}else{
				return false;
			}
		}
		Log::record(date("Y-m-d H:i:s").' '.$flag.':');
		Log::record($dataPost);
		if(is_array($dataPost)){
			if(isset($dataPost['account_id'])){
				// 开通验证session验证
				if(Session::has('member_id')){
					$member_id = Session::get('member_id');
					if($member_id !=$dataPost['account_id']){
						return false;
					}
				}
				return $dataPost;
			}
		}

		return false;
	}

	/**
	 * 返回错误信息
	 * @param [type]  $operation  [方法名]
	 * @param [type]  $message    [要返回的信息]
	 * @param integer $res        [返回结果]
	 */
	private function ErrorInfo($operation,$message,$res=1){
		$result['result'] =$res ;
		$result['operation'] = $operation;
		$result['result_message'] = $message;
		return json_encode($result);
	}

	/**
	 * 获得ticke_type对应的消耗的钻石说参数数组
	 */
	private function GetGameCards(){
		return [1=>10,2=>16,3=>24];
	}

	/**
	 * 获得ticke_type对应的游戏局数参数数组
	 */
	private function GetGameNums()
	{
		return [1=>10,2=>15,3=>20,4=>30];
	}


	/**
	 * 第一次点链接进入房间，更新自己状态account_status=0 online_status=1 jointime  room_id，如果是第二次点击进入则指更新 online_status=1  jointime
	 *  返回申请加入房间的信息 当前局数  总局数 玩法 玩家:id 昵称 头像  积分 account_status 列表返回加入成功。
	 *  房间内准备好的人大于等于4人，锁定房间，但是曾经进入房间的人可以再次进来围观
	 *  account_status（自己的游戏状态） 0：准备 2：坐下 3：    8：游戏结束
	 *  游戏总次数玩完，roomStatus=1，再次进入则会直接返回战绩列表
	 * @param
	 * dataGet=[//get提交参数
	 *     'account_id'=>,//会员账号
	 *     'room_number'=>//房间号
	 * ]
	 * @return 如果游戏没有结束则返回
	 * success: {"result": 0, "account_id": 5840, "operation": "PrepareJoinRoom", "players": [{"id": 6695, "nickname": "杰仔", "account_score": 350, "sort": null, "jointime": null }, {"id": 6737, "nickname": "小磊", "account_score": -85, "sort": null, "jointime": null }, {"id": 6738, "nickname": "愿时光间歇性飞逝", "account_score": -265, "sort": null, "jointime": null } ], "data": {"room_status": 2, "room_number": "9977070", "total_num": 20, "game_num": 6, "banker_mode": 2, "game_type": 5, "ticket_type": 2 }, "result_message": "围观"}
	 *
	 * faile: ['result'=>1,'operation'=>'PrepareJoinRoom','result_message'=>'房间人数已满！']
	 *     ['result'=>1,'operation'=>'PrepareJoinRoom','result_message'=>'无效信息']
	 * @return 如果游戏结束则返回战绩列表
	 *  success: {"result": 0, "account_id": 5841, "operation": "GameOver", "data": [{"nickname": "杰仔", "score": 350 }, {"nickname": "小磊", "score": -85 }, {"nickname": "愿时光间歇性飞逝", "score": -265 } ] }
	 *  faile: ['result'=>1,'operation'=>'PrepareJoinRoom','result_message'=>'无效信息']
	 */
	public function JoinRoom(){
		$dataPost=$this->GetPost('PrepareJoinRoom');
		$dataPost=array(
			'account_id'=>5897,
			'data'=>array(
				'room_id' =>375587
			)
		);
		if(!$dataPost){
			return $this->ErrorInfo('PrepareJoinRoom','无效信息');
		}
		//1. 判断是否是会员
		$member = $this->IsMember($dataPost['account_id'],'id,room_id');
		if(!$member){
			return $this->ErrorInfo('PrepareJoinRoom','无效信息');
		}
		//2. 判断房间是否存在,游戏总次数是否结束，是否锁定
		$room=$this->RoomIsExist($dataPost);
		if(!$room){
			return $this->ErrorInfo('PrepareJoinRoom','无效信息');
		}elseif($room->roomStatus==1){//游戏已经结束返回游戏战绩
			return $this->GetMembersScore($room->id,$member->id);
		}elseif($room->islock==1){
			if(empty($detail)){//房间锁定并且曾经没有进来过，则返回人满
				return $this->ErrorInfo('PrepareJoinRoom','房间人数已满！');
			}
		}
		$detail=Db::table('t_historyscore')->where(['account_id' =>$dataPost['account_id'],'room_id'=>$room->id])->find();

		// 3. 房间到达4人准备好（account_status>=2）就锁定，并返回false
		$allmember=$this->RoomIsLock($room->id,'id');
		if($allmember===false){
			if(!empty($detail)){//如果曾来过房间，还是可以再次进来
				return $this->ErrorInfo('PrepareJoinRoom','房间人数已满！');
			}
		}
		// 4.初始化自己进入房间后的状态
		if($member->room_id==$room->id){//第二次进入
			$data=['online_status'=>1,'jointime'=>time()];
		}else{//第一次进入
			$data=['room_id'=>$room->id,'online_status'=>1,'account_status'=>0 ,'jointime'=>time()];
		}
		$this->UpdateMemberById($data,$member->id);
		// 5. 获取房间内所有人的id,nickname,jointime,sort
		$player=$this->GetOlinePlayerInfo($room->id);
		// 6. 返回进房询问结果
		$result['result'] = 0;
		$result['account_id'] = $dataPost['account_id'];
		$result['operation'] = "JoinRoom";
		$result['players'] = $player;// 选手信息
		// 房间的的游戏信息
		$result['data']['room_status'] = $room->room_status;
		$result['data']['room_number'] = $room->room_number;
		$result['data']['total_num'] = $room->total_num;
		$result['data']['game_num']=$room->game_num;
		$result['data']['banker_mode']=$room->banker_mode;
		$result['data']['game_type']=$room->game_type;
		$result['data']['ticket_type'] = $room->ticket_type;
		$result['data']['rule_type'] = $room->rule_type;  // 1 房主支付
		$result['data']['score_type'] = $room->score_type; // 1比大小
		$result['data']['base_score'] = $room->base_score; // 10分
		$result['result_message'] = "围观";//var_dump($result);exit;
		return json_encode($result);
	}

	/**
	 * 判断房间是否存在(可以通过id，或者room_number查询)
	 * @param [array] $data  数组
	 * @return bool false | obj 房间对象
	 */
	private function RoomIsExist($post){
		//判断房间是否存在
		if(isset($post['data']['room_id'])){
			$where=['id' => $post['data']['room_id']];
		}elseif(isset($post['data']['room_number'])){
			$where=['room_number' => $post['data']['room_number']];
		}else{
			return false;
		}
		$room = model('room')->where($where)->find();
		return $room;
	}

	/**
	 * 判断房间是否应该被锁 在线人数大于等于4人就锁定房间
	 * @param [type] $id 房间id
	 * @param [type] $filed 要查询的字段
	 */
	private function RoomIsLock($id,$filed="*"){
		$id+=0;
		$allmember = Db::query("select $filed from t_member where room_id =$id and account_status >=2");
		$allCount = count($allmember);
		if($allCount >= 4){
			$this->LockRoom($id);
			return false;
		}
		return $allmember;
	}

	private function LockRoom($id){
		model('room')->where(['id' => $id])->update(['islock' => 1]);
	}

	private function UpdateMemberById($data,$id){
		db('member')->where('id',$id)->update($data);
	}

	/**
	 * 按座位和加入时间排序，获得在线选手信息
	 * @param [int] $room_id [房间id]
	 */
	private function GetOlinePlayerInfo($room_id){
		$all = Db::query("select id,account_status,nickname,account_score,sort,jointime from t_member where room_id =$room_id and online_status=1 order by sort asc ,jointime asc ");
		if(empty($all))$all=[];
		$ret=[];
		foreach ($all as  $val) {
			$val['nickname']=$this->DecodeNickname($val['nickname'],0);
			$ret[]=$val;
		}
		return $ret;
	}

	/**
	 * 将昵称解码
	 * @param [type]  $nicknames [昵称]
	 * @param integer $isArray   [是否是数组的标识]
	 */
	private function DecodeNickname($nicknames,$isArray=0){
		if($isArray){
			$result=[];
			foreach ($nicknames as $nickname) {
				$result[]=@base64_decode($nickname);
			}
			return $result;
		}else{
			$result=@base64_decode($nicknames);
			return $result;
		}
	}

	/**
	 * 坐下：玩家属于准备状态 发送当前房间坐下的人数  account_status=2 代表坐下
	 * workman 发消息给房主，客户端人数满2 倒计时开始游戏
	 *@param
	 * dataPost=[
	 *     'account_id'=>,//会员账号
	 *     'data'=>[
	 *         'room_id'=>,//房间id
	 *         'sort'=>//座位 （1  2  3  4）
	 *     ]
	 * ]
	 */
	public function SitDown(){
		$dataPost=$this->GetPost('SitDown');
		$dataPost=array(
			'account_id'=>5897,
			'data'=>array(
				'room_id' =>375587,
				'sort'	=>2
			)
		);
		if(!$dataPost or !isset($dataPost['data']['sort'])){
			return $this->ErrorInfo('SitDown','无效信息');
		}
		//1.座位号错误
		if($dataPost['data']['sort']<0 or $dataPost['data']['sort']>4){
			return $this->ErrorInfo('SitDown','座位号错误');
		}
		//2.判断是否是会员
		$member = $this->IsMember($dataPost['account_id'],'id');
		if(!$member){
			return $this->ErrorInfo('SitDown','无效信息');
		}
		//3.判断房间是否存在,
		$room=$this->RoomIsExist($dataPost);
		if(!$room){
			return $this->ErrorInfo('SitDown','无效信息');
		}

		// 3. 房间准备好的人等于4人就锁定，返回false，否则取得准备好人员的sort的信息
		$allmember=$this->RoomIsLock($room->id,'id,sort');
		if($allmember===false){
			return $this->ErrorInfo('SitDown','房间人数已满！');
		}
		// 4. 验证座位号是否被占用
		$sorts=array_column($allmember,'sort');
		if(in_array($dataPost['data']['sort'], $sorts)){
			//座位号错误
			return $this->ErrorInfo('SitDown','此座位号已被占用');
		}
		// 5. 查询积分，初始化个人积分
		$detail=Db::table('t_historyscore')->where(['account_id' =>$dataPost['account_id'],'room_id'=>$room->id])->find();
		$myScore=0;
		if($detail)$myScore=$detail['score'];
		// 6. 更新个人状态
		$data=['online_status'=>1, 'score_board'=>$myScore, 'account_score'=>$myScore, 'account_status'=>2, 'sort'=>$dataPost['data']['sort'], ];

		$this->UpdateMemberById($data,$member->id);

		// 返回准备好的信息
		$result['result'] = 0;
		$result['operation'] = "SitDown";
		$result['data']['total_num'] = $room['total_num'];
		$result['data']['room_id'] = $room['id'];
		$result['data']['room_number'] = $room['room_number'];
		$result['data']['room_status'] = $room['room_status'];
		$result['data']['game_num'] = $room['game_num'];
		$result['data']['playercount']=count($allmember)+1;
		$result['result_message'] = "坐下，准备好！";
		return json_encode($result);
	}

	/*
	 * 游戏自动开始
	 */
	public function GameAutoStart() {
		$dataPost=$this->GetPost('SitDown');
		$dataPost=array(
			'account_id'=>array(5897,6695),
			'data'=>array(
				'room_id' =>375587,
				'sort'	=>2
			)
		);
		if(!$dataPost or !isset($dataPost['data']['room_id']) or empty($dataPost['data']['room_id'])){
			return $this->ErrorInfo('GameStart','无效信息');
		}
		if(!$dataPost or !isset($dataPost['account_id']) or empty($dataPost['account_id'])){
			return $this->ErrorInfo('GameStart','无效信息');
		}
		$roomId = $dataPost['data']['room_id'];

		//1.验证在线状态 online_status = 1，account_id
		foreach($dataPost['account_id'] as $v){
			$toMember = Db::query("select id from t_member where id={$v} and online_status = 1 and  room_id =" . $roomId);
			if(!$toMember) return $this->ErrorInfo('GameStart','玩家不存在');
		}

		//2. 房间游戏局数+1  game_num+1
		$roomInfo = model('room')->where(array('id' => $roomId))->find()->toArray();
		$game_num = $roomInfo['game_num'] + 1;
		model('room')->where(array('id' => $roomId))->update(array('game_num' => $game_num, 'roomStatus' => 1));

		//3.更改账户状态 account_status=2 的 用户 改成 account_status=3  2代表坐下，3代表游戏开始
		model('member')->where(array('room_id' => $roomId, 'account_status' => 2))->update(array('account_status' => 3));

		//4.返回
		$dataStart['result'] = 0;
		$dataStart['operation'] = "GameStart";
		$dataStart['result_message'] = "游戏开始了";
		$dataStart['limit_time'] = 10;
		$dataStart['game_num'] = $game_num;
		echo json_encode($dataStart);
	}

	/*
	 * 抢庄
	 * @is_grab 是否抢庄
	 * @account_id  room_id
	 * 玩家点击抢庄或者不抢  修改account_status =4(不抢庄)  account_status=5(抢庄)
	 * 查新 account_status =3 的人数还有没有   没有说明坐下的人数全部完成抢庄环节  随机一个庄家出来
	 * return 推送玩家信息  前端判断 is_banker 是否存在， 存在抢庄结束 开始下一轮
	 */
	public function GrabBanker() {
		$dataPost=$this->GetPost('GrabBanker');
		$dataPost=array(
			'account_id'=>5897,
			'data'=>array(
				'room_id' =>375587,
				'sort'	=>2,
				'is_grab'=>1  // 1抢庄  0不抢
			)
		);
		if(!$dataPost or !isset($dataPost['data']['room_id']) or empty($dataPost['data']['room_id'])){
			return $this->ErrorInfo('GrabBanker','无效信息');
		}
		if(!$dataPost or !isset($dataPost['account_id']) or empty($dataPost['account_id'])){
			return $this->ErrorInfo('GrabBanker','无效信息');
		}
		if(!$dataPost or !isset($dataPost['data']['is_grab']) or empty($dataPost['data']['is_grab'])){
			return $this->ErrorInfo('GrabBanker','无效信息');
		}
		$room_id = $dataPost['data']['room_id'];
		$is_grab = $dataPost['data']['is_grab'];
		$account_id = $dataPost['account_id'];

		//获取当前房间被推送的玩家
		$toMember = Db::query("select id from t_member where online_status = 1 and  room_id =" . $room_id);
		$toMember = array_column($toMember, 'id');
		$data['to'] = $toMember;
		//更改玩家状态
		if($is_grab==1){
			//抢庄
			model('member')->where(array('id' => $account_id))->update(array('account_status' => 5,'is_grab' => $is_grab));
		}elseif($is_grab==0){
			//不抢庄
			model('member')->where(array('id' => $account_id))->update(array('account_status' => 4,'is_grab' => $is_grab));
		}else{
			return $this->ErrorInfo('GrabBanker','field error: is_grab');
		}

		//抢庄是否结束
		$count = Db::query("select count(*) as count from t_member where online_status = 1 and account_status = 3 and room_id =" . $room_id );
		$grabCount = $count[0]['count'];
		if($grabCount == 0){
			//完成抢庄环节 随机一个庄家
			$grab_members = Db::query("select id from t_member where online_status = 1 and account_status = 5 and  room_id =" . $room_id);
			$grab_members = array_column($grab_members, 'id');
			shuffle($grab_members);
			$data['is_banker'] = $grab_members[0];
			//没有人抢庄
			if(count($grab_members) == 0){
				shuffle($toMember);
				$data['is_banker'] = $toMember[0];
			}

			//更新庄家信息
			model('member')->where(array('room_id'=>$room_id))->update(array('is_banker' => 0));
			model('member')->where(array('id' => $data['is_banker'],'room_id'=>$room_id))->update(array('is_banker' => 1));
		}
		//当前玩家信息
		$memberInfo = model('member')->where(array('id' => $account_id))->find()->toArray();
		$data['data'] = $memberInfo;
		return json_encode($data);
	}

	/*
	 * 下注  下注完成发牌
	 * @is_multiples 是否加注
	 * @multiples  加注倍率
	 * @account_id  room_id
	 * 玩家加注或者不加  修改account_status =6(不加注)  account_status=7(加注)
	 * 查新 下注和没下注的人数 与 游戏中的人数 是否相等   没有说明坐下的人数全部完成下注环节
	 * return 推送玩家信息  前端判断 finish_multiples 是否存在， 存在加注结束 开始下一步
	 */
	public function PlayerMultiples() {
		$dataPost=$this->GetPost('GrabBanker');
		$dataPost=array(
			'account_id'=>5897,
			'data'=>array(
				'room_id' =>375587,
				'sort'	=>2,
				'is_multiples'=>1,  // 1加注  0加注
				'multiples'=>5  // 1 代表 1分    3  5  10
			)
		);
		if(!$dataPost or !isset($dataPost['data']['room_id']) or empty($dataPost['data']['room_id'])){
			return $this->ErrorInfo('PlayerMultiples','无效信息');
		}
		if(!$dataPost or !isset($dataPost['account_id']) or empty($dataPost['account_id'])){
			return $this->ErrorInfo('PlayerMultiples','无效信息');
		}
		if(!$dataPost or !isset($dataPost['data']['is_multiples']) or empty($dataPost['data']['is_multiples'])){
			return $this->ErrorInfo('PlayerMultiples','无效信息');
		}
		if(!$dataPost or !isset($dataPost['data']['multiples']) or empty($dataPost['data']['multiples'])){
			return $this->ErrorInfo('PlayerMultiples','无效信息');
		}
		$room_id = $dataPost['data']['room_id'];
		$is_multiples = $dataPost['data']['is_multiples'];
		$multiples = $dataPost['data']['multiples'];
		$account_id = $dataPost['account_id'];

		//获取当前房间被推送的玩家
		$toMember = Db::query("select id from t_member where online_status = 1 and  room_id =" . $room_id);
		$toMember = array_column($toMember, 'id');
		$data['to'] = $toMember;
		//更改玩家状态
		if($is_multiples==1){
			//押注
			model('member')->where(array('id' => $account_id))->update(array('account_status' => 6,'is_multiples' => $is_multiples,'multiples' => $multiples));
		}elseif($is_multiples !== 1){
			//不压
			model('member')->where(array('id' => $account_id))->update(array('account_status' => 7,'is_multiples' => $is_multiples,'multiples' => 0));
		}

		//押注是否结束
		//游戏中的人数
		$count = Db::query("select count(*) as count from t_member where online_status = 1 and account_status >= 3 and room_id =" . $room_id );
		$gameCount = $count[0]['count'];
		//下注和没下注的人数
		$count = Db::query("select count(*) as count from t_member where online_status = 1 and (account_status = 6 or account_status = 7) and room_id =" . $room_id );
		$multiplesCount = $count[0]['count'];

		if($gameCount == $multiplesCount){
			//押注结束
			$data['finish_multiples'] = 1;
			//发牌
			$data['players'] = array();
			foreach($toMember as $v){
				$data['players'][$v] = $this->getRand(4);
				//保存牌的数据
				model('member')->where(array('room_id' => $room_id,'id'=>$v,'online_status'=>1))->update(array('pai' => implode(',',$data['players'][$v])));
			}
		}
		//当前玩家信息
		$memberInfo = model('member')->where(array('id' => $account_id))->find()->toArray();
		$data['data'] = $memberInfo;
		return json_encode($data);
	}

	/*
	 * 摊牌
	 * 推送摊牌信息  计算得分
	 * @account_id  room_id
	 * 'account_status' => 8 摊牌
	 * 'pai' => [[E6,G27],[A12,G19]]
	 */
	public function PlayerShowCard() {
		$dataPost=$this->GetPost('GrabBanker');
		$dataPost=array(
			'account_id'=>5897,
			'data'=>array(
				'room_id' =>375587,
				'sort'	=>2,
			),
			'pai'=> array(
				array('E6','E6'),
				array('F7','G27')
			)
		);
		if(!$dataPost or !isset($dataPost['data']['room_id']) or empty($dataPost['data']['room_id'])){
			return $this->ErrorInfo('PlayerShowCard','无效信息');
		}
		if(!$dataPost or !isset($dataPost['account_id']) or empty($dataPost['account_id'])){
			return $this->ErrorInfo('PlayerShowCard','无效信息');
		}

		$room_id = $dataPost['data']['room_id'];
		$account_id = $dataPost['account_id'];

		//游戏中的人数
		$count = Db::query("select count(*) as count from t_member where online_status = 1 and account_status >= 3 and room_id =" . $room_id );
		$gameCount = $count[0]['count'];

		// 将自己的状态改为已摊牌
		model('member')->where(array('id' => $account_id, 'room_id' => $room_id, 'account_status' => 8))->update(array('account_status' => 8));

		//获取当前房间被推送的玩家
		$toMember = Db::query("select id from t_member where online_status = 1 and  room_id =" . $room_id);
		$toMember = array_column($toMember, 'id');
		$data['to'] = $toMember;

		//当前玩家信息
		$memberInfo = model('member')->where(array('id' => $account_id))->find()->toArray();
		$data['data'] = $memberInfo;
		//验证客户端发来的牌



		//当前摊牌玩家的牌的结果  牌的类型和点数
		$this->getPlayerPaiInfo($dataPost['pai']);
	}

	/*
	 * 牌的类型  值
	 */
	public function getPlayerPaiInfo($arrPai){
		if(!$arrPai) return false;
		$cardsType = $this->cardsType();
		$cardsValue = $this->cardsValue();

		$data = array();
		foreach($arrPai as $k=>$val){
			//特殊牌型
			$typeIndex = implode('_',$val);
			if(isset($cardsType[$typeIndex])){
				$data[$k]['type'] = $cardsType[$typeIndex];
				$data[$k]['value'] = $cardsValue[$typeIndex];
			}else{
				//点数
				$specialCard = array('G15','G25','G17','G27','G18','G28','G19','G29');
				$point = 0;
				foreach($val as $v){
					//截取字母之后的点数   特殊牌截取两位
					if(!in_array($v,$specialCard)){
						//截取一位
						$point += substr($v,1);
					}else{
						$point += substr($v,2);
					}
				}
				$point = $point%10;
				$data[$k]['type'] = $point;
				$data[$k]['value'] = 0;
			}
		}

		//排序
		foreach($data as $key=>$value){

		}
	}

	/*
	 * 所有的牌
	 */
	public function allCards(){
		return array(
			0=>'A12',1=>'A12',   //双天
			2=>'B2',3=>'B2',     //双地
			4=>'C8',5=>'C8',     //双人
			6=>'D4',7=>'D4', 	 //双鹅
			8=>'E10',9=>'E10',   //双梅
			10=>'E6',11=>'E6',   //双长三
			12=>'E4',13=>'E4',   //双板凳
			14=>'F7',15=>'F7',   //双高脚
			16=>'F6',17=>'F6',   //双零霖
			18=>'F11',19=>'F11', //双斧头
			20=>'F10',21=>'F10', //双红头
			22=>'G15',23=>'G25', //杂五
			24=>'G17',25=>'G27', //杂七
			26=>'G18',27=>'G28', //杂八
			28=>'G19',29=>'G29', //杂九
			30=>'H3',31=>'H6',   //至尊
		);
	}

	/*
	 * 牌的类型
	 */
	public function cardsType(){
		return array(
			'A12_A12'=>'双天',
			'B2_B2'=>'双地',
			'C8_C8'=>'双人',
			'D4_D4'=>'双鹅',
			'E10_E10'=>'双梅',
			'E6_E6'=>'双长三',
			'E4_E4'=>'双板凳',
			'F7_F7'=>'双高脚',
			'F6_F6'=>'双零霖',
			'F11_F11'=>'双斧头',
			'F10_F10'=>'双红头',
			'G15_G25'=>'杂五','G12_G15'=>'杂五',
			'G17_G27'=>'杂七','G27_G17'=>'杂七',
			'G18_G28'=>'杂八','G28_G18'=>'杂八',
			'G19_G29'=>'杂九','G29_G19'=>'杂九',
			'H3_H6'=>'至尊',  'H6_H3'=>'至尊',
			'G29_A12'=>'天九皇','G12_A29'=>'天九皇',
			'G28_A12'=>'天杠','G12_A28'=>'天杠',
			'G28_B2'=>'地杠','G2_B28'=>'地杠',
			'G17_A12'=>'天高九','G12_A17'=>'天高九',
			'F7_B2'=>'地高九','B2_F7'=>'地高九',
		);
	}

	/*
   * 牌型的值，用于比大小
   */
	public function cardsValue(){
		return array(
			'H3_H6'=>13,  'H6_H3'=>13,

			'A12_A12'=>12,
			'B2_B2'=>11,
			'C8_C8'=>10,
			'D4_D4'=>9,
			'E10_E10'=>8,
			'E6_E6'=>8,
			'E4_E4'=>8,
			'F7_F7'=>7,
			'F6_F6'=>7,
			'F11_F11'=>7,
			'F10_F10'=>7,
			'G15_G25'=>6,'G25_G15'=>6,
			'G17_G27'=>6,'G27_G17'=>6,
			'G18_G28'=>6,'G28_G18'=>6,
			'G19_G29'=>6,'G29_G19'=>6,
			'G29_A12'=>5,'G12_A29'=>5,
			'G28_A12'=>4,'G12_A28'=>4,
			'G28_B2'=>3,'G2_B28'=>3,
			'G17_A12'=>2,'G12_A17'=>2,
			'F7_B2'=>1,'B2_F7'=>1,
		);
	}


	/*
	 * 获得随机牌
	 */
	private function getRand($n){
		$allCards = $this->allCards();
		$num = range(0,31);
		shuffle($num);
		for ($i=0; $i < $n; $i++) {
			 $arr[] = $allCards[$num[$i]];
		}
		return $arr;
	}

}
